package org.ala.tiktools.sharddb.mybatis.pager.with_order;

import org.ala.tiktools.mybatis.interfaces.AbstractOrderBy;
import org.ala.tiktools.mybatis.pager.PagerCountDO;
import org.ala.tiktools.sharddb.mybatis.executor.ShardExecutor;
import org.ala.tiktools.sharddb.mybatis.router.ShardInfo;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ala
 * @date 2025-03-08 21:59
 */
public class ShardPageCountDO {
    /**
     *  总数量
     */
    protected int total;
    /**
     *  极值
     */
    protected Object extreme;
    /**
     *  每个分表的查询结果
     */
    protected Map<ShardInfo, PagerCountDO> shardResult;


    public static ShardPageCountDO build(AbstractOrderBy orderBy, Map<ShardInfo, PagerCountDO> results) {
        ShardPageCountDO r = new ShardPageCountDO();

        r.shardResult = new HashMap<>();
        Object e1 = null;
        for (Map.Entry<ShardInfo, PagerCountDO> e : results.entrySet()) {
            ShardInfo shardInfo = e.getKey();
            PagerCountDO d = e.getValue();
            r.shardResult.put(shardInfo, d);
            r.total += d.getCount();
            if (e1 == null) {e1 = d.getExtreme();}
            else if (d.getExtreme() != null){
                Object e2 = d.getExtreme();
                int c = orderBy.compare(e1, e2);
                boolean b = orderBy.getCurrentItem().isAsc();
                e1 = (b && c <= 0) || (!b && c >= 0) ? e1 : e2;
            }
        }
        r.extreme = e1;
        return r;
    }


    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public Object getExtreme() {
        return extreme;
    }

    public void setExtreme(Object extreme) {
        this.extreme = extreme;
    }

    public Map<ShardInfo, PagerCountDO> getShardResult() {
        return shardResult;
    }

    public void setShardResult(Map<ShardInfo, PagerCountDO> shardResult) {
        this.shardResult = shardResult;
    }
}
